package org.yi.web.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.common.Constants;
import org.yi.core.enums.BlockTargetEnum;
import org.yi.core.enums.BlockTypeEnum;
import org.yi.core.enums.PostStateEnum;
import org.yi.core.http.HttpClient;
import org.yi.core.model.Pagination;
import org.yi.web.account.entity.AccountEntity;
import org.yi.web.block.entity.BlockEntity;
import org.yi.web.category.entity.CategoryEntity;
import org.yi.web.post.entity.PostEntity;
import org.yi.web.sys.entity.SiteEntity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;

/**
 * Controller基类， 放一些Controller中的公共方法
 * @author qq
 *
 */
public class BaseController extends Controller {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	/** http get请求 **/
	protected static final String METHOD_GTE = "get";
	/** http post请求 **/
	protected static final String METHOD_POST = "post";
	
	/** 请求处理成功 */
	protected static final String SUCCESS = "1";
	
	/** 请求处理失败 */
	protected static final String ERROR = "0";
	
	protected Map<String, Object> blocks = new HashMap<String, Object>();
	
	public SiteEntity getSite() {
		SiteEntity site = CacheKit.get(Constants.CACHE_KEY_FOREVER, "site");
		if(site == null) {
			site = SiteEntity.dao.getSite();
		}
		return site;
	}
	
	/**
	 * 在request对象中添加返回信息
	 * @param msg		返回前台的信息
	 */
	protected void addMessage(String msg){
		setAttr("msg", msg);
	}
	/**
	 * 在request对象中添加返回信息
	 * @param msg		返回前台的信息
	 * @param params	参数
	 */
	protected void addMessage(String msg, Object... params) {
		msg = String.format(msg, params);
		addMessage(msg);
	}
	/**
	 * 在request对象中添加返回前台的错误信息
	 * @param msg
	 */
	protected void addError(String msg){
		setAttr("error", msg);
	}
	/**
	 * 在request对象中添加返回信息
	 * @param msg		返回前台的信息
	 * @param params	参数
	 */
	protected void addError(String msg, Object... params) {
		msg = String.format(msg, params);
		addError(msg);
	}
	
	/**
	 * 跳转到全局错误页面
	 */
	public void error() {
		render("error.html");
	}
	
	/**
	 * 获取客户端请求方式，如get和post等
	 * @return
	 */
	protected final String getHttpMethod(){
		return getRequest().getMethod();
	}
	
	/**
	 * 是否是get方法访问
	 * @return
	 */
	protected boolean isGetMethod(){
		return METHOD_GTE.equalsIgnoreCase(getHttpMethod());
	}
	
	/**
	 * 是否是post方法访问
	 * @return
	 */
	protected boolean isPostMethod(){
		return METHOD_POST.equalsIgnoreCase(getHttpMethod());
	}
	
	protected Pagination getPager() {
		int pageNumber = StringUtils.isBlank(getPara("pageNumber")) ? 1 : getParaToInt("pageNumber");
		int pageSize = StringUtils.isBlank(getPara("pageSize")) ? Constants.DEFAULT_PAGESIZE : getParaToInt("pageSize");
		return new Pagination(pageNumber, pageSize);
	}
	
	protected AccountEntity getCurrentUser() {
		return (AccountEntity) SecurityUtils.getSubject().getSession(true).getAttribute(Constants.KEY_LOGIN_ACCOUNT);
	}
	
	public AccountEntity getFrontUser() {
		return getRequest() == null ? null : (AccountEntity) getSession(true).getAttribute(Constants.FRONT_LOGIN_USER);
	}
	
	protected void loadBlocks(){
		loadBlocks(BlockTargetEnum.ALL);
	}
	
	protected void loadBlocks(BlockTargetEnum target) {
		if(target == null) target = BlockTargetEnum.ALL;
		List<BlockEntity> blockList = CacheKit.get(Constants.CACHE_KEY_FOREVER, "blockList");
		if(blockList == null || blockList.size() == 0) {
			blockList = BlockEntity.dao.getByTarget(target);
			CacheKit.put(Constants.CACHE_KEY_FOREVER, "blockList", blockList);
		}
		for(final BlockEntity b : blockList) {
			if(BlockTypeEnum.STANDARD.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
				// 标准文章列表
				blocks.put(b.getStr("name"), CacheKit.get(Constants.CACHE_KEY_MID, b.getStr("name"), new IDataLoader() {
					
					@Override
					public Object load() {
						try {
							return PostEntity.dao.getByBlock(b);
						} catch (Exception e) {
							logger.error("get standard article list error: " + e.getMessage(), e);
							e.printStackTrace();
						};
						return null;
					}
				}));
			} else if(BlockTypeEnum.CUSTOMIZE.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
				//指定文章
				
				blocks.put(b.getStr("name"), CacheKit.get(Constants.CACHE_KEY_MID, b.getStr("name"), new IDataLoader() {
					
					@Override
					public Object load() {
						try {
							return PostEntity.dao.getByIdListForBlock(b);
						} catch (Exception e) {
							logger.error("get customize article list error: " + e.getMessage(), e);
						}
						return null;
					}
				}));
			}  else if (BlockTypeEnum.HTML.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
                // HTML区块
				blocks.put(b.getStr("name"), b.get("content"));
            }  else if (BlockTypeEnum.RANDOM.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
				blocks.put(b.getStr("name"), CacheKit.get(Constants.CACHE_KEY_MID, b.getStr("name"), new IDataLoader() {
					
					@Override
					public Object load() {
						try {
							return PostEntity.dao.getRandom(b);
						} catch (Exception e) {
							logger.error("get random article list error: " + e.getMessage(), e);
						}
						return null;
					}
				}));
            } else if (BlockTypeEnum.CATEGORY.getCode().equalsIgnoreCase(String.valueOf(b.get("type")))) {
                // 随机文章列表(同类)
				blocks.put(b.getStr("name"), CacheKit.get(Constants.CACHE_KEY_MID, b.getStr("name"), new IDataLoader() {
					
					@Override
					public Object load() {
						try {
							return PostEntity.dao.getRandom(b, getPara("cid"));
						} catch (Exception e) {
							logger.error("get random article list error: " + e.getMessage(), e);
						}
						return null;
					}
				}));
            }
		}
		setAttr("blocks", blocks);
	}
	
	/**
	 * 获取评论最多的文章列表
	 * @return
	 */
	public List<PostEntity> getHotArticle() {
		return CacheKit.get(Constants.CACHE_KEY_SHORT, "dsHotArticle", new IDataLoader() {
			@Override
			public Object load() {
				try {
					String requestURL = Constants.config.getString("duoshuo.baseurl") 
							+ "/sites/listTopThreads.json?short_name="+ Constants.config.getString("duoshuo.short_name") 
							+"&num_items="+Constants.DEFAULT_PAGESIZE;
					String replyNumJson = new HttpClient().get(requestURL);
					JSONObject duoshuoResult = JSONObject.parseObject(replyNumJson);
					if(duoshuoResult.getInteger("code") == 0) {
						List<Integer> idList = new ArrayList<Integer>();
						JSONArray jsonArray = duoshuoResult.getJSONArray("response");
						for(int i=0;i<jsonArray.size();i++) {
							JSONObject o = jsonArray.getJSONObject(i);
							idList.add(o.getInteger("thread_key"));
						}
						return PostEntity.dao.getByIdList(idList.toArray());
					}
				} catch (Exception e) {
					logger.error("获取热门文章出错：" + e.getMessage(), e);
				}
				return null;
			}
		});
	}
	
	public JSONArray getRecentReply() {
		return CacheKit.get(Constants.CACHE_KEY_SHORT, "dsRecentReply", new IDataLoader() {
			@Override
			public Object load() {
				try {
					String jsonStr = new HttpClient().get(Constants.config.getString("duoshuo.recent_post.url"));
					JSONObject duoshuoResult = JSONObject.parseObject(jsonStr);
					return duoshuoResult.getJSONArray("response");
				} catch (Exception e) {
					logger.error("获取最新评论出错：" + e.getMessage(), e);
					return null;
				}
			}
		});
	}
	
	public void setHeader() {
		setAttr("site", getSite());
		setAttr("categoryList", CacheKit.get(Constants.CACHE_KEY_FOREVER, "categoryList", new IDataLoader() {
			@Override
			public Object load() {
				return CategoryEntity.dao.getAll();
			}
		}));
		setAttr("categoryMap", CacheKit.get(Constants.CACHE_KEY_FOREVER, "categoryMap", new IDataLoader() {
			@Override
			public Object load() {
				return CategoryEntity.dao.getIdTitleMap();
			}
		}));
		setAttr("categoryIdAliasMap", CacheKit.get(Constants.CACHE_KEY_FOREVER, "categoryIdAliasMap", new IDataLoader() {
			@Override
			public Object load() {
				return CategoryEntity.dao.getIdAliasMap();
			}
		}));
		setAttr("authorMap", CacheKit.get(Constants.CACHE_KEY_FOREVER, "authorMap", new IDataLoader() {
			@Override
			public Object load() {
				return AccountEntity.dao.getIdTitleMap();
			}
		}));
		setAttr("stateMap", CacheKit.get(Constants.CACHE_KEY_FOREVER, "stateMap", new IDataLoader() {
			@Override
			public Object load() {
				return PostStateEnum.toMap();
			}
		}));
	}
}
